#include "../tools.h"


class Solution {
private:
    int min_int = 0x80000000;
    int max_int = 0x7fffffff;
public:
    int myAtoi(string s) {
        int p = 0;
        int size = s.size();
        bool neg = false;
        while(p < size && (s[p] == ' ')) ++p;
        if(p == size) return 0;

        
        if(s[p] == '-') {neg = true; ++p;}
        else if(s[p] == '+') ++p;

        while(p < size && s[p] == '0') ++p;

        int res = 0;
        while(s[p] >= '0' && s[p] <= '9') {
            if(!neg && (res > max_int / 10 || res == max_int / 10 && (s[p] - '0') >= max_int % 10))
                return max_int;
            if(neg && (res * (-1) < min_int / 10 || res * -1 == min_int / 10 && (s[p] - '0') * -1 <= min_int % 10))
                return min_int;

            res *= 10;
            res += (s[p] - '0');
            ++p;
        }
        return neg ? -res : res;
    }
};

int main(int argc, char const *argv[])
{
    Solution sol;

    cout << sol.myAtoi("   -42") << endl;
    cout << sol.myAtoi("   000000-42") << endl;
    cout << sol.myAtoi("   -000000000000000000042") << endl;
    cout << sol.myAtoi("4193 with words") << endl;
    cout << sol.myAtoi("2147483647") << endl;
    cout << sol.myAtoi("2147483648") << endl;
    cout << sol.myAtoi("-2147483648") << endl;
    cout << sol.myAtoi("-2147483649") << endl;

    return 0;
}
